#!BPY
'''
从火炬之光 mine.dat 文件中导入 矿洞 所需要的所有的 场景组件
'''
bl_info = {
	"name" : "torchlight tileset import",
	"author" : "liyonghelpme",
	"version" : {1, 0, 0},
	"blender": (2, 70, 0),
	"location": "File > Import > layout (.dat)",
	"description" : "tile set import",
	"warning" : "",
	"wiki_url" : "http://www.baidu.com",
	"category" : "Import-Export",
}

__version__ = "1.2.3"

import logging
handle = logging.FileHandler("/Users/liyong/blender.log")
logger = logging.getLogger()
logger.addHandler(handle)
logger.setLevel(logging.INFO)

import bpy
import glob
import os
import re
import xml.sax
import xml.sax.handler

import bmesh
import mathutils
from mathutils import Vector
from mathutils import Matrix
import codecs
from bpy.props import *
import subprocess

def log(msg):
    logger.info(msg)


horsnap = re.compile("HORIZONTALSNAP:(\d+(\.\d+)?)")
versnap = re.compile("VERTICALSNAP:(\d+(\.\d+)?)")
#read lines
#read if match PIECE
piece = re.compile("\[PIECE\]")
endpiece = re.compile("\[/PIECE\]")
fi = re.compile("FILE:([\w/\.\d]+)")
colFile = re.compile("COLLISIONFILE:([\w/\.\d]+)")
guid = re.compile("GUID:(\d+)")

mediaPart = re.compile("media[\w\d/\.]+")
def fileselection_callback(filename):
	log("Reading Layout File %s..." % filename)
	ret = mediaPart.findall(filename)
	rootDir = filename.replace(ret[0], '')
	log("root Dir:%s" % rootDir)

	try:
		lines = codecs.open(filename, encoding="utf16", mode="rb").readlines()
	except:
		lines = codecs.open(filename, encoding="utf8", mode="rb").readlines()
		pass
	count = 0
	for l in lines:
		fileName = None
		colName = None
	
		ret = fi.findall(l)
		if len(ret) > 0:
			#bpy.ops.wm.read_homefile()

			fileName = ret[0]
			log("export File:"+fileName)
			bpy.ops.import_scene.ogre_mesh(filepath=os.path.join(rootDir,fileName), clearMesh=True)
			count += 1
			#break

		ret = colFile.findall(l)
		if len(ret) > 0:
			#bpy.ops.wm.read_homefile()

			colName = ret[0]
			log("export ColFile:"+colName)
			bpy.ops.import_scene.ogre_mesh(filepath=os.path.join(rootDir, colName), clearMesh=True)
			count += 1
			#break
		#if count >= 2:
		#	break


class IMPORT_OT_LAYOUT(bpy.types.Operator):
    bl_idname = "import_scene.layout"
    bl_description = 'Import from torchlight layout format (.dat)'
    bl_label = "Import layout" +' v.'+ __version__
    bl_space_type = "PROPERTIES"
    bl_region_type = "WINDOW"
    bl_options = {'UNDO'}

    filepath = StringProperty(
            subtype='FILE_PATH',
            )

	
    def draw(self, context):
        layout0 = self.layout
        layout = layout0.box()
        col = layout.column()


    def execute(self, context):
        fileselection_callback(self.filepath)
        return {'FINISHED'}

    def invoke(self, context, event):
        wm = context.window_manager
        wm.fileselect_add(self)
        return {'RUNNING_MODAL'}

		

def menu_func(self, context):
    self.layout.operator(IMPORT_OT_LAYOUT.bl_idname, text="layout (.dat)")   

def register():
    bpy.utils.register_module(__name__)
    bpy.types.INFO_MT_file_import.append(menu_func)

if __name__ == "__main__":
	register()